import Vue from "vue";
import VueRouter from "vue-router";

import { getToken } from "../utils/token";
Vue.use(VueRouter);

const routes = [
  {
    path: "/",
    component: () => import("@/views/index.vue"),
    // 路由重定向
    redirect: "/article",
    // 添加个子页面
    children: [
      {
        path: "article",
        component: () => import("@/views/article.vue"),
      },
      {
        path: "collection",
        component: () => import("@/views/collection.vue"),
      },
      {
        path: "favorite",
        component: () => import("@/views/favorite.vue"),
      },
      {
        path: "user",
        component: () => import("@/views/user.vue"),
      },
    ],
  },
  { path: "/login", component: () => import("@/views/login.vue") },
  { path: "/register", component: () => import("@/views/register.vue") },
  {
    path: "/articleDetail/:id",
    component: () => import("@/views/article-detail.vue"),
  },
];

const router = new VueRouter({
  routes,
});

router.beforeEach((to, from, next) => {
  // 检查是否 登录

  // 登录、注册页面 不需要检查
  if (to.path === "/login" || to.path === "/register") {
    // 不检查，允许访问
    next();
    return;
  }
  // 不是登录页面、注册页面。检查登录
  // 如果没有token 跳转到登录页
  if (!getToken()) {
    next("/login");
    return;
  }
  // 有token 允许放行
  next();
});

export default router;
